package utils;


import cn.hutool.json.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import java.util.Random;


public class SendMsg {

    private static final String  accessKeyId="LTAIBNBeSDadrW9u";
    private static final String  accessSecret="f2kCsHT8zY1Gc6ZHsMUJoXEJi4ax1X";
    private static final String  signName="尚峰的应用";
    private static final String  templateCode="SMS_200693294"; // 模板名称
    private static final String  regionId="cn-hangzhou";
    private static final String  version="2017-05-25";
    private static final String  doMain="dysmsapi.aliyuncs.com";
    private static final String  action="SendSms";

    public static  String sendMsg(String phone) {

        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessSecret);

        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(doMain);
        request.setSysVersion(version);
        request.setSysAction(action);
        request.putQueryParameter("RegionId",regionId);
        request.putQueryParameter("PhoneNumbers",phone);
        request.putQueryParameter("SignName",signName);
        request.putQueryParameter("TemplateCode",templateCode);

        String code = verificationCode();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",code);
        request.putQueryParameter("TemplateParam",jsonObject.toString());

        try {
            CommonResponse response = client.getCommonResponse(request);
            return code;
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return  null;
    }

    private static  String verificationCode(){
        String sources = "0123456789";//用于生成验证码
        Random random = new Random();
        StringBuffer flag = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            flag.append(sources.charAt(random.nextInt(9))+"");
        }
        return flag.toString();
    }
}
